package cn.shentianlan.service.impl;

import cn.shentianlan.criteria.ClassroomCriteria;
import cn.shentianlan.domain.dto.ClassroomDTO;
import cn.shentianlan.domain.entity.Classroom;
import cn.shentianlan.domain.entity.Course;
import cn.shentianlan.mapper.ClassroomMapper;
import cn.shentianlan.service.ClassService;
import cn.shentianlan.service.ClassroomService;
import cn.shentianlan.utils.BaseUtils;
import cn.shentianlan.utils.DataUtils;
import cn.shentianlan.utils.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author 陈俊源
 * @Description TODO
 * @Date 2021/4/20
 * @Version 1.0
 */
@Service
public class ClassroomServiceImpl implements ClassroomService {

    @Autowired
    private ClassroomMapper classroomMapper;

    @Override
    public Result saveOrUpdate(ClassroomDTO classroomDTO) {
        Classroom classroom = BaseUtils.copyProperties(classroomDTO, Classroom.class);
        if (classroomDTO.getId()==null){
            Long id = DataUtils.assignId();
            classroom.setId(id);
            classroomMapper.saveClassroom(classroom);
        }else {
            classroomMapper.updateClassroom(classroom);
        }
        return Result.success(classroom.getId());
    }

    @Override
    public Result findClassroomByCriteria(ClassroomCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(),criteria.getPageSize(),false);
        List<Classroom> classroomList = classroomMapper.findClassroomByCriteria(criteria);
        Integer count = classroomMapper.getCount();
        List<ClassroomDTO> classroomDTOList = new ArrayList<ClassroomDTO>();
        for (Classroom classroom :classroomList ) {
            ClassroomDTO classroomDTO = bulidClassroomDTO(classroom);
            classroomDTOList.add(classroomDTO);
        }
        PageInfo<ClassroomDTO> pageInfo = new PageInfo<ClassroomDTO>(classroomDTOList);
        pageInfo.setTotal(count.longValue());
        return Result.success(pageInfo);
    }

    @Override
    public Result getClassroomById(Long id) {
        if (id==null){
            return Result.fail("id为空，无法查询到课室信息");
        }
        Classroom classroom = classroomMapper.getClassroomById(id);
        if (classroom == null){
            return Result.fail("获取该id对应的课室信息出错");
        }
        return Result.success(classroom);
    }

    @Override
    public Result deleteClassroomById(Long id) {
        if (id==null){
            return Result.fail("id为空，无法查询到课室信息");
        }
        classroomMapper.deleteClassroomById(id);
        return Result.success(id);
    }

    private ClassroomDTO bulidClassroomDTO(Classroom classroom) {
        ClassroomDTO classroomDTO = BaseUtils.copyProperties(classroom, ClassroomDTO.class);
        return classroomDTO;
    }
}
